package com.k.kc.util.base64.base64url;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Logger;

/**
 * Created by 170623910 on 2021/9/21.
 */
public class Message implements Serializable {
    private static final long serialVersionUID = 42L;

    transient String code;
    transient Object[] parameters;
    transient ResourceBundle bundle;

    /**
     * Constructor.
     *
     * @param key the message catalog (resource bundle) key
     * @param logger a logger with an associated resource bundle
     * @param params the message substitution parameters
     */
    public Message(String key, Logger logger, Object...params) {
        this(key, logger.getResourceBundle(), params);
    }

    /**
     * Constructor.
     *
     * @param key the message catalog (resource bundle) key
     * @param catalog the resource bundle
     * @param params the message substitution parameters
     */
    public Message(String key, ResourceBundle catalog, Object...params) {
        code = key;
        bundle = catalog;
        parameters = params;
    }

    @Override
    public String toString() {
        String fmt = null;
        try {
            if (null == bundle) {
                return code;
            }
            fmt = bundle.getString(code);
        } catch (MissingResourceException ex) {
            return code;
        }
        return MessageFormat.format(fmt, parameters);
    }

    public String getCode() {
        return code;
    }

    public Object[] getParameters() {
        return parameters;
    }

    private void writeObject(java.io.ObjectOutputStream out)
            throws IOException {
        out.writeUTF(toString());
    }
    private void readObject(java.io.ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        code = in.readUTF();
        bundle = null;
        parameters = null;
    }
}
